﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Imageo.bintje;
using log4net;
using System.Threading;

namespace Imageo.ui
{
    public partial class TrailSearch : System.Web.UI.Page
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        protected void Page_Load(object sender, EventArgs e)
        {
            trailTableOriginal.Visible = false;
            spanReferenceTrail.Visible = false;
            imageTable.Visible = false;

                try
                {
                    bintje.imageoSession currentSession = Session["BintjeSession"] as imageoSession;
                    string searchString = Request.QueryString["searchStr"];
                    
                    string onlyOwn = Request.QueryString["onlyOwn"];
                    
                    string imageidStr = Request.QueryString["imageid"];
                    int imageid = 0;

                    string trailidStr = Request.QueryString["trailid"];
                    int trailid = 0;

                    // We don't have any session available, load world map

                    ServiceAPI service = new ServiceAPI();
                    trailListResponse response;
                    trailListResponse response2;
                    similarImageResponse imgResponse;

                    if (!int.TryParse(imageidStr, out imageid))
                    {
                        imageid =0;
                    }

                    if (!int.TryParse(trailidStr, out trailid))
                    {
                        trailid = 0;
                    }

                    if (imageid<=0)
                    {

                        if (onlyOwn != null && onlyOwn == "true")
                        {
                            spanTitle.InnerText = "My Trails";

                            // GET OWN TRAILS
                            if (currentSession == null) Response.Redirect("~/UI/ErrorLoginFirst.aspx");
                            if (log.IsErrorEnabled) log.Debug("Calling: service.getMyTrails(currentSession)");
                            response = ServiceHelper.HandleBintjeErrors(this, service.getMyTrails(currentSession));
                        }
                        else
                        {
                            spanTitle.InnerText = "Search results";

                            if (!string.IsNullOrEmpty(searchString))
                            {
                                if (log.IsErrorEnabled) log.Debug("Calling: service.findTrails(searchString)");
                                response = ServiceHelper.HandleBintjeErrors(this, service.findTrails(searchString));
                            }
                            else
                            {
                                if (log.IsErrorEnabled) log.Debug("Calling: service.getWorldTrails()");
                                response = ServiceHelper.HandleBintjeErrors(this, service.getWorldTrails());
                            }
                        }
                        trailTable.LoadTrails(response.trailList);

                        lnkSortByDistance.Visible = false;
                        lnkSortBySimilarity.Visible = false;
                    }
                    else
                    {
                        if (trailid > 0)
                        {
                            spanTitle.InnerText = "Similar trails";

                            // We have an imageid... let's find similar trails

                            if (log.IsErrorEnabled) log.Debug("Calling: service.getSimilarTrails()");

                            similarImageRequest sireq = new similarImageRequest();
                            sireq.imageId = imageid;
                            sireq.innerRadius = 0;
                            sireq.outerRadius = 1000000;
                            sireq.maximumNumber = 100;
                            sireq.trailstoexclude = new int?[1];
                            sireq.trailstoexclude[0] = trailid;
                            sireq.session = currentSession;

                            lnkSortByDistance.Visible = true;
                            lnkSortBySimilarity.Visible = true;

                            response = ServiceHelper.HandleBintjeErrors(this, service.getSimilarTrails(sireq));

                            trailTable.LoadTrails(response.trailList);

                            trailRequest treq = new trailRequest();
                            treq.session = currentSession;
                            treq.trailId = trailid;
                            trailResponse tmpRespose = ServiceHelper.HandleBintjeErrors(this, service.getTrailDetails(treq));

                            response2 = new trailListResponse();
                            List<trailWrapper> tmpList = new List<trailWrapper>();

                            tmpList.Add(new trailWrapper()
                            {
                                created = tmpRespose.trail.created,
                                createdSpecified = tmpRespose.trail.createdSpecified,
                                description = tmpRespose.trail.description,
                                id = tmpRespose.trail.id,
                                imageUrl = tmpRespose.trail.imageUrl,
                                latitude = 0,
                                longitude = 0,
                                numberOfannotations = (tmpRespose.trail.annotations != null ? tmpRespose.trail.annotations.Length : 0),
                                publicTrail = tmpRespose.trail.publicTrail,
                                title = tmpRespose.trail.title,
                                userlogin = tmpRespose.trail.user.login,
                                usernick = tmpRespose.trail.user.nickName
                            });

                            response2.trailList = tmpList.ToArray();

                            // Now load reference trail
                            trailTableOriginal.Visible = true;
                            trailTableOriginal.LoadTrails(response2.trailList);
                            trailTableOriginal.ShowPager = false;
                            spanReferenceTrail.Visible = true;
                        }
                        else
                        {
                            imageTable.Visible = true;
                            trailTable.Visible = false;
                            spanTitle.InnerText = "Similar images";

                            if (log.IsErrorEnabled) log.Debug("Calling: service.getSimilarImages()");

                            similarImageRequest sireq = new similarImageRequest();
                            sireq.imageId = imageid;
                            sireq.innerRadius = 0;
                            sireq.outerRadius = 1000000;
                            sireq.maximumNumber = 100;
                            sireq.trailstoexclude = null;

                            lnkSortByComments.Visible = false;
                            lnkSortByLocation.Visible = false;
                            lnkSortByDistance.Visible = false;
                            lnkSortBySimilarity.Visible = false;
                            // Now load reference trail
                            trailTableOriginal.Visible = false;
                            spanReferenceTrail.Visible = false;

                            imgResponse = ServiceHelper.HandleBintjeErrors(this, service.getSimilarImages(sireq));
                            imageTable.LoadImages(imgResponse.images);
                        }
                    }

                }
                catch (ThreadAbortException) { }
                catch (Exception exc)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.Error(exc.Source + " - " + exc.Message);
                    }
                    Response.Redirect("~/UI/ErrorGeneric.aspx");
                }
        }

        protected void lnkSortByTitle_Click(object sender, EventArgs e)
        {
            trailTable.SortByTitle();
        }

        protected void lnkSortByComments_Click(object sender, EventArgs e)
        {
            trailTable.SortByComments();
        }

        protected void lnkSortByDistance_Click(object sender, EventArgs e)
        {
            trailTable.SortByDistance();
        }

        protected void lnkSortBySimilarity_Click(object sender, EventArgs e)
        {
            trailTable.SortBySimilarity();
        }
    }
}
